#include "scrollview.h"
#include <float.h>
#include <QPainter>
#include <QPaintEvent>
#include <QTimer>
#include <QApplication>
#include <QMouseEvent>
#include <QPalette>
#include "common.h"



int ScrollView::m_id = qRegisterMetaType<ScrollView*>();

ScrollView::ScrollView(QWidget *parent)
    : ViewObject(parent)
    , m_scrollTimer(new QTimer(this))
    , m_curIndex(0)
    , m_scrollviewParam(NULL)
{
    setWindowFlags(Qt::FramelessWindowHint);
    connect(m_scrollTimer, SIGNAL(timeout()), this, SLOT(updateIndex()));
    setAttribute(Qt::WA_DeleteOnClose);
#ifdef __linux__
    setFocusPolicy(Qt::NoFocus);
#else
    setFocusPolicy(Qt::StrongFocus);
#endif

    if (m_objectParam == NULL)
    {
        m_objectParam = new ParamObject;
    }

    if(m_scrollviewParam == NULL)
    {
        m_scrollviewParam = new ScrollViewParam;
    }

    m_color = QColor(Qt::white);

    m_bk_color = QColor(Qt::black);

}

ScrollView::~ScrollView()
{
    DestoryObject();
}

void ScrollView::DestoryObject()
{
    HideObject();

    if(m_objectParam != NULL)
    {
        delete  m_objectParam;
    }
    m_objectParam = NULL;

    if (m_scrollviewParam != NULL)
    {
        delete m_scrollviewParam;
    }
    m_scrollviewParam = NULL;

    close();

}

void ScrollView::HideObject()
{
    setParent(NULL);
    stop();
    hide();
}

void ScrollView::ShowObject(QWidget *parent, QString filename, QString prefix, ProtocolData * ptr_data)
{
    Q_UNUSED(prefix);
    Q_UNUSED(ptr_data);
    if(m_scrollviewParam == NULL)
    {
        return;
    }
    if(m_objectParam == NULL)
    {
        return;
    }

    setParent(parent);

    location(m_objectParam->GetX(), m_objectParam->GetY(),
                m_objectParam->GetWidth(), m_objectParam->GetHeight());

    if (m_scrollviewParam->m_textFormat != "")
    {
        QStringList format_list = m_scrollviewParam->m_textFormat.split("\n");

        for (int i = 0; i < format_list.size(); i++)
        {
            if(format_list.at(i).contains(";"))
            {
               int pre_index;
               int suffx_index;
               pre_index = format_list.at(i).indexOf("(");
               suffx_index = format_list.at(i).indexOf(")");
               QStringList rgblist = format_list.at(i).mid(pre_index + 1, suffx_index - pre_index - 1).split(",");
               int r = rgblist.at(0).trimmed().toInt();
               int g = rgblist.at(1).trimmed().toInt();
               int b= rgblist.at(2).trimmed().toInt();
               if (format_list.at(i).startsWith("color"))
               {
                   m_color = QColor::fromRgb(r, g, b);
               }
               else if (format_list.at(i).startsWith("background-color"))
               {
                   m_bk_color = QColor::fromRgb(r, g, b);
               }
            }
            else
            {
                QFont f;
                if (f.fromString(format_list.at(i)))
                {
                    m_font = f;
                }
            }
        }

    }

    show();

    start();

}

void ScrollView::GetAttribute(std::string& attribute)
{
    std::string jsonStr;
    Json::Value base;
    Json::StreamWriterBuilder writerBuilder;
    std::ostringstream os;

    base["zindex"] = QString::number(m_objectParam->GetIndex()).toStdString();
    base["stid"] = QString::number(m_objectParam->GetStId()).toStdString();
    base["x"] = QString::number(m_objectParam->GetX()).toStdString();
    base["y"] = QString::number(m_objectParam->GetY()).toStdString();
    base["w"] = QString::number(m_objectParam->GetWidth()).toStdString();
    base["h"] = QString::number(m_objectParam->GetHeight()).toStdString();
    base["name"] = m_objectParam->GetName().toStdString();
    base["content"] = m_scrollviewParam->m_textContent.toStdString();
    base["style"] = m_scrollviewParam->m_textFormat.toStdString();
    base["stid"] = QString::number(m_objectParam->GetStId()).toStdString();
    base["stepwidth"] = QString::number(m_scrollviewParam->m_stepWidth).toStdString();
    base["steptime"] = QString::number(m_scrollviewParam->m_stepTime).toStdString();

    std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
    jsonWriter->write(base, &os);
    jsonStr = os.str();

    attribute = jsonStr;
}

void ScrollView::SetAttribute(std::string jsonStr)
{
    bool res;
    JSONCPP_STRING errs;
    Json::Value root;
    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
    res = jsonReader->parse(jsonStr.c_str(), jsonStr.c_str()+jsonStr.length(), &root, &errs);

    if (!res || !errs.empty())
    {
         LOG_QDEBUG<<__FUNCTION__<<"json parse faild"<<QString::fromStdString(errs);
    }

    if(CheckJsonValueType(root, "zindex", Json::stringValue))
    {
        m_objectParam->SetIndex(QString::fromStdString(root["zindex"].asString()).toInt());
    }

    if(CheckJsonValueType(root, "stid", Json::stringValue))
    {
        m_objectParam->SetStId(QString::fromStdString(root["stid"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"x",Json::stringValue))
    {
        m_objectParam->SetX(QString::fromStdString(root["x"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"y",Json::stringValue))
    {
        m_objectParam->SetY(QString::fromStdString(root["y"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"w",Json::stringValue))
    {
         m_objectParam->SetWidth(QString::fromStdString(root["w"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"h",Json::stringValue))
    {
         m_objectParam->SetHeight(QString::fromStdString(root["h"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"name",Json::stringValue))
    {
         m_objectParam->SetName(QString::fromStdString(root["name"].asString()));
    }

    if(CheckJsonValueType(root,"content",Json::stringValue))
    {
        m_scrollviewParam->m_textContent = QString::fromStdString(root["content"].asString());
    }

    if(CheckJsonValueType(root,"style",Json::stringValue))
    {
        m_scrollviewParam->m_textFormat = QString::fromStdString(root["style"].asString());
    }

    if(CheckJsonValueType(root,"stepwidth",Json::stringValue))
    {
        m_scrollviewParam->m_textFormat = QString::fromStdString(root["stepwidth"].asString()).toInt();
    }

    if(CheckJsonValueType(root,"steptime",Json::stringValue))
    {
        m_scrollviewParam->m_textFormat = QString::fromStdString(root["steptime"].asString()).toInt();
    }
    if (CheckJsonValueType(root, "idtype", Json::stringValue))
    {
        m_objectParam->SetStIdType(QString::fromStdString(root["idtype"].asString()));
    }
}

void ScrollView::ParseXML(QDomElement* xmlDomEle)
{
    if(m_scrollviewParam == NULL)
    {
        m_scrollviewParam = new ScrollViewParam;
    }
    m_objectParam->SetIndex((xmlDomEle->attribute("zindex","0")).toInt());
    m_objectParam->SetStId((xmlDomEle->attribute("stid","0")).toInt());
    m_objectParam->SetX((xmlDomEle->attribute("x","0")).toInt());
    m_objectParam->SetY((xmlDomEle->attribute("y","0")).toInt());
    m_objectParam->SetWidth((xmlDomEle->attribute("w","0")).toInt());
    m_objectParam->SetHeight((xmlDomEle->attribute("h","0")).toInt());
    m_objectParam->SetName(xmlDomEle->attribute("name",""));

    QDomNodeList paramlist = xmlDomEle->childNodes();
    for(int listcnt = 0; listcnt < paramlist.count(); listcnt++)
    {
        QDomElement param = paramlist.item(listcnt).toElement();
        if(param.isComment()||param.isNull())
        {
            continue;
        }
        QString temp = param.attribute("content", "hello scroll");
        if(temp != "")
        {
            m_scrollviewParam->m_textContent = temp;
        }
        temp = param.attribute("style", "");
        if(temp != "")
        {
            m_scrollviewParam->m_textFormat = temp;
        }
        temp = param.attribute("stepwidth", "");
        if (temp != "")
        {
            m_scrollviewParam->m_stepWidth = temp.toInt();
        }
        temp = param.attribute("steptime", "");
        if (temp != "")
        {
            m_scrollviewParam->m_stepTime = temp.toInt();
        }
    }

}

void ScrollView::PacketXML(QDomElement* dom)
{
    QDomDocument document;
    *dom = document.createElement("item");
    dom->setAttribute("type",m_objectParam->GetObjectName());
    dom->setAttribute("zindex",QString::number(m_objectParam->GetIndex()));
    dom->setAttribute("stid",QString::number(m_objectParam->GetStId()));
    dom->setAttribute("x",QString::number(m_objectParam->GetX()));
    dom->setAttribute("y",QString::number(m_objectParam->GetY()));
    dom->setAttribute("w",QString::number(m_objectParam->GetWidth()));
    dom->setAttribute("h",QString::number(m_objectParam->GetHeight()));
    dom->setAttribute("name",m_objectParam->GetName());

    QDomElement dom1 = document.createElement("param");
    dom1.setAttribute("content", m_scrollviewParam->m_textContent);
    dom->appendChild(dom1);

    QDomElement dom2 = document.createElement("param");
    dom2.setAttribute("style", m_scrollviewParam->m_textFormat);
    dom->appendChild(dom2);

    QDomElement dom3 = document.createElement("param");
    dom3.setAttribute("steptime", m_scrollviewParam->m_stepTime);
    dom->appendChild(dom3);

    QDomElement dom4 = document.createElement("param");
    dom4.setAttribute("stepwidth", m_scrollviewParam->m_stepWidth);
    dom->appendChild(dom4);
}


void ScrollView::start()
{
    m_scrollTimer->start(m_scrollviewParam->m_stepTime);
}

void ScrollView::stop()
{
    m_scrollTimer->stop();
}

void ScrollView::updateIndex()
{
    update();
    m_curIndex++;
    QFontMetrics fm(m_font);
    int textWidth = fm.width(m_scrollviewParam->m_textContent);
    if ( (m_curIndex * m_scrollviewParam->m_stepWidth) > (textWidth + width()) )
    {
        m_curIndex = 0;
    }

}

void ScrollView::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

//    QStylePainter painter(this);
//    //用style画背景 (会使用setstylesheet中的内容)
//    QStyleOption opt;
//    opt.initFrom(this);
//    opt.rect=rect();
//    painter.drawPrimitive(QStyle::PE_Widget, opt);

    QPainter painter(this);

    painter.fillRect(this->rect(), QBrush(QColor(m_bk_color)));

    painter.setPen(m_color);
    painter.setFont(m_font);

    QFontMetrics fm(m_font);
    const QRect rectangle(this->width() - m_scrollviewParam->m_stepWidth * m_curIndex, 0,\
                          fm.width(m_scrollviewParam->m_textContent), height());

    painter.drawText(rectangle, Qt::AlignVCenter, m_scrollviewParam->m_textContent);

    if (mSelect)
    {
        QPen pen(Qt::blue, 4, Qt::DotLine);
        painter.setPen(pen);
        painter.drawRect(rect());
    }
    else
    {
        painter.setPen(Qt::NoPen);
        painter.drawRect(rect());
    }

}
